const BYTES_PER_CHUNK = 1 * 1024 * 1024; // 1 mb el tamaño de las partes  
var total_files = 0;

function drag_drop_init(field, params) {  
    var dropZone = document.getElementById('dnd_drop_zone');
    dropZone.addEventListener('dragover', handleDragOver, false);
    dropZone.addEventListener('drop', handleFileSelect, false);
}

function uploadFile(blob, i) {
    var start = 0;
    var end;
    var index = 0;

    // Calcular el numero de partes a enviar
    var slices = Math.ceil(blob.size / BYTES_PER_CHUNK);
    var total_slices = slices;
                    
    while(start < blob.size) {                  
        end = start + BYTES_PER_CHUNK;
        if (end > blob.size) {
            end = blob.size;
        }
        
        // Parte del archivo
        var chunk = blob.slice(start, end);

        // Form para enviar en el post
        var fd = new FormData();
        fd.append("file", chunk);
        fd.append("name", blob.name);
        fd.append("index", index);
        
        // Ajax para realizar la subida
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                slices--;
                
                var loaded = (total_slices-slices > 0 ? (total_slices-slices) / total_slices : 0);
                var percentLoaded = Math.round(loaded * 97);
      
                $("div[id='file_progressbar["+i+"]'] .percent").animate({
                    width: percentLoaded + '%'
                }, 500);
                //$("div[id='file_progressbar["+i+"]'] .percent").text(percentLoaded + '%');
                
                // Si terminaron de subir todas las partes las une
                if (slices == 0) {
                    mergeFile(blob, total_slices, i);
                }
            }
        };
        xhr.open("POST", WWW + "remotes/request/DRAG_DROP/ajaxUploadFile", true);
        xhr.send(fd);
        
        start = end;
        index++;
    }
}

function mergeFile(blob, slices, file) {
    // Form para enviar en el post
    var fd = new FormData();
    fd.append("name", blob.name);
    fd.append("index", slices);

    // Ajax para realizar el merge
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var jdata = $.parseJSON(xhr.responseText);
            if (jdata.status == "error") {
                console.log("ERROR (mergeFile) " + jdata.desc);
            }
            else {
                $("[id='dnd_file["+file+"]']").val(jdata.target);
                setTimeout(function() {
                    var del_button = '<img src="/images/default/bt_del.gif" alt="Eliminar" class="acciones" onclick="deleteUploadedFile('+file+');">';
                    $("div[id='file_progressbar["+file+"]']").fadeOut(200).parent().html(del_button);
                }, 1000);
            }
        }
    };
    xhr.open("POST", WWW + "remotes/request/DRAG_DROP/ajaxMergeFile", true);
    xhr.send(fd);
}

function deleteUploadedFile(file) {
    var filename = $("[id='dnd_file["+file+"]']").val();
    $("tr[id='dnd_file_row["+file+"]']").fadeOut(200).remove();
    
    // Ajax para realizar la subida
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var jdata = $.parseJSON(xhr.responseText);
            if (jdata.status == "error") {
                console.log("ERROR (deleteUploadedFile) " + jdata.desc);
            }
        }
    };
    xhr.open("POST", WWW + "remotes/request/DRAG_DROP/ajaxDeleteFile/", true);
    xhr.send();
}

function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    // Obtiene los archivos del evento drag and drop
    var files = evt.dataTransfer.files;
    
    // Por cada archivo agrega una fila en la tabla y hace la subida
    for (var i = 0, f; f = files[i]; i++) {
        var html = '<tr id="dnd_file_row[' + (total_files) + ']">';
        html += '<input type="hidden" name="dnd_file[' + total_files + ']" id="dnd_file[' + total_files + ']" />';
        html += '<td><strong>' + escape(f.name) + '</strong></td>';
        html += '<td>(' + (empty(f.type) ? 'n/a' : f.type) + ')</td>';
        html += '<td>' + formatBytes(f.size) + '</td>';
        html += '<td><div class="progressbar" id="file_progressbar[' + total_files + ']"><div class="percent"></div></div></td>';
        html += '</tr>';
        $('#dnd_files_table').append(html);   
        
        uploadFile(f, total_files);
        
        total_files++;
    }
}

function handleDragOver(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
